<template>
  <div class="disp_map_file">
    <!-- <template slot="title">
      <b style="font-size: large;">文章信息</b><i class="header-icon el-icon-info"></i>
    </template> -->
    <el-row v-if="type">
      <el-col class="dispFilter" :span="6">
        <span v-if="type === 'author'">个人信息</span>
        <span v-else-if="type === 'proc'">会议信息</span>
        <el-card v-if="type== 'proc'" style="margin-right: 30px; margin-top: 9%">
          <div slot="header" style="color: cadetblue;">
            <span>{{ this.data.origintitle }}</span>
          </div>
          <div>
            <div>年份：{{ this.data.year }}</div>
            <div>期刊：{{
                subNull(this.data.publisher, subNull(this.data.journal, "unknown"))
              }}
            </div>
          </div>
        </el-card>
        <el-card v-else style="margin-right: 30px; margin-top: 9%">
          <div slot="header" style="color: cadetblue;">
            <span>{{ this.id }}</span>
          </div>
          <div v-if="isShow">
            <Chart :id="id"/>
          </div>
        </el-card>
      </el-col>

      <el-col class="dispArticle" :span="18">
        <span :v-loading="isLoading"
              element-loading-text="拼命加载中"
              element-loading-spinner="el-icon-loading">文章列表</span>
        <div style="margin-top: 3%;min-height: 300px;width: 100%;" class="toLeft"
             :v-loading="isLoading"
        >
          <el-card
            v-for="(article,index) in articleList"
            :key="index"
            class="dispCard"
          >
            <el-row>
              <el-col :span="3" style="font-size: x-large;">
                <i class="el-icon-download" @click="handleChange(article.sourceAsMap)"></i>
                <i class="el-icon-share"></i>
                <i class="el-icon-delete"></i>
              </el-col>

              <el-col :span="20">
                <div>
                  <span v-for="(a, index) in article['sourceAsMap'].author" :key="index">
                    <span v-if="index!==0">,</span>
                    <el-link style="margin-left: 3px; color: cadetblue;"
                             @click="jumpFromAuthor(a)"
                    >{{ a }}</el-link>
                  </span>
                </div>
                <div>
                  <div style="font-weight: bold">
                    <div v-html="article['sourceAsMap'].title">
                    </div>
                  </div>
                  <div>
                    <b>|</b> <span>{{ article['sourceAsMap'].year }}</span>
                    <b>|</b> <span>期刊：{{
                      subNull(article['sourceAsMap'].publisher, subNull(article.sourceAsMap.journal, "unknown"))
                    }}</span>
                    <b>|</b> <span>类型：{{ getType(article.index, " unknown index") }}</span>
                  </div>
                </div>
              </el-col>
              <el-col :span="24">
                <el-collapse @change="handleChange(article.sourceAsMap,article.id,article.index,index)">
                  <el-collapse-item title="展示更多信息">
                    <!--                      {{ dispArticleArr[index] }}-->
                    <div v-loading="!dispArticleArr[index]" style="min-height: 100px;">
                      <el-form v-if="dispArticleArr[index]">

                        <el-form-item label="下载地址">
                          <el-link type="primary" :underline="false"
                                   :disabled="article.sourceAsMap.ee[0]===null||article.sourceAsMap.ee[0]===undefined"
                                   :href="subNull(article.sourceAsMap.ee[0], '/') ">
                            点击此处跳转至下载页面
                          </el-link>
                        </el-form-item>

                        <el-form-item label="研究领域">
                          <span v-for="a in subNull(article.sourceAsMap.extend.field,[])">
                            <span style="margin-left: 3px; color: cadetblue;"
                            >{{ a }}</span>
                          </span>
                        </el-form-item>
                        <el-form-item label="引用文献">
                          <el-table
                            :data="subNull(article.sourceAsMap.extend.citeInfo,[])">
                            <el-table-column label="标题">
                              <template slot-scope="scope">
                                <el-link @click="changeQuery(scope.row.title,offset)">
                                  {{ scope.row.title }}
                                </el-link>
                              </template>
                            </el-table-column>
                            <el-table-column label="出版年份" prop="year" sortable></el-table-column>
                            <el-table-column label="被引数" prop="numCitedBy" sortable></el-table-column>
                            <el-table-column label="引用数" prop="numCiting" sortable></el-table-column>
                          </el-table>
                        </el-form-item>
                      </el-form>
                    </div>
                  </el-collapse-item>
                </el-collapse>

              </el-col>
            </el-row>
          </el-card>
        </div>
        <el-row style="margin-top: 1%; margin-bottom: 1%; text-align: center">
          <el-col :span="24">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="curPage"
              :page-sizes="[10,20,50,100, 200, 500]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalArticles">
            </el-pagination>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <div v-else>
      当前暂无展示详情信息，请返回查询页面
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import Vue from 'vue';
import mapper from "../lib/mapper";
import Chart from './Chart'


export default {

  mounted() {
    this.id = this.$route.params.id
    this.type = this.$route.params.type
    this.data = this.$route.params.data
    if (!this.id) {
      this.$alert('请回到搜索界面选择信息', '提示')
      // this.$router.push({path: 'search'})
    } else {
      this.getList()
    }
  },
  components: {Chart},
  data: function () {
    return {
      type: '',
      id: '',
      data: {},
      mapper: mapper,
      curPage: 1,
      pageSize: 10,
      sortOption: ['按相关度排序', '按时间排序'],
      selectedSort: '按相关度排序',
      articleList: [],
      totalArticles: 400,
      dispArticleArr: new Array(this.pageSize),
      itemType: {
        'article': '杂志期刊文章',
        'inproceedings': '会议文章',
        'book': '书籍',
        'incollection': '书籍文章',
        'phdthesis': '博士论文',
        'mastersthesis': '硕士论文',
        'www': '网站'
      },
      isShow: true,
      isLoading: false,
    }

  },
  methods: {
    getList() {
      var url = ''
      if (this.type === 'author') {
        url = '/api/getArticleByAuthorId'
      } else if (this.type === 'proc') {
        url = '/api/getArticleByConferenceId'
      }
      this.isLoading = true;
      axios.post(url, {
        keys: this.id,
        curPage: this.curPage,
        pageSize: this.pageSize,
        filter: {
          ascOrder: false,
          orderBy: 'year'
        },
      }).then(res => {
        if (res.data.success) {
          console.log("作者信息查询成功", res)
          this.isLoading = false;
          for (var i = 0; i < res.data.data['hits'].length; i++) {
            Vue.set(this.articleList, i, res.data.data['hits'][i])
          }
          this.totalArticles = res.data.data['totalHits'].value
          this.dispArticleArr = new Array(this.articleList.length).fill(false)

        } else {
          this.$message.error(res.data.info)
        }
      }).catch(err => {
        this.isLoading = false;
      })
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.getList()
    },
    handleCurrentChange(val) {
      this.curPage = val;
      this.getList()
      window.scrollTo(0, 0)
    },

    async handleChange(src, id, index, offset) {
      console.log(src, id)
      src.disp = 0;

      let isInfoChange = false, isExtendChange = false, ssId = null;
      if (src.extend === undefined) {
        isExtendChange = true;
        src.extend = {}
      } else if (src.extend['ssId'] === undefined || src.extend['ssId'] === null) {
        isExtendChange = true;
      } else {
        ssId = src.extend['ssId'];
      }

      if (ssId === null) {
        await axios.post('https://www.semanticscholar.org/api/1/search',
          mapper.generateDetailQuery(src.title)).then(res => {
          if (res.data.results !== null && res.data.results.length > 0) {
            let topMatch = res.data.results[0]
            src.extend.ssId = topMatch.id
            ssId = topMatch.id
            src.extend['doiInfo'] = topMatch['doiInfo']
            src.extend['abstract'] = topMatch['paperAbstract']['text']
            src.extend['venue'] = topMatch['venue']['text']
            src.extend['field'] = topMatch['fieldsOfStudy']
          }
        }).catch(err => console.log(err))
      }
      if (ssId !== null && src.extend.citeInfo === undefined) {
        await axios.post("https://www.semanticscholar.org/api/1/search/paper/" + ssId + "/citations",
          mapper.citationParam).then(res => {
          isExtendChange = true;
          src.extend.citeInfo = res.data.results.map(obj => {
            return {
              title: obj.title.text,
              year: obj.year,
              numCitedBy: obj.numCitedBy,
              numCiting: obj.numCiting
            }
          })
        })
      }
      if (isExtendChange) {
        await axios.post('/api/updateSingle',
          {
            index: index,
            id: id,
            content: {
              extend: src.extend
            }
          }).then(res => {
          console.log(res)
          this.$message(res.data.info)
        })
      }
      console.log(src.extend)
      Vue.set(this.dispArticleArr, offset, true)

    },

    subNull(val, alt) {
      if (val !== null && val !== undefined) {
        return val;
      } else {
        return alt;
      }
    },
    getType(val, alt) {
      if (val !== null && val !== undefined) {
        return this.itemType[val]
      } else {
        return alt;
      }
    },

    jumpFromAuthor(name) {
      this.id = name
      this.type = 'author'
      this.getList()
      this.isShow = false
      setTimeout(() => {
        this.isShow = true
      }, 0)
    },

    changeQuery(str, offset) {
      this.$router.push({
        name: 'search', params: {
          crossQuery: true,
          queryStr: str,
          searchPath: "searchArticleByKW",
          offset: offset
        }
      })
    }

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.disp_map_file {
  text-align: left;
}

.toLeft {
  text-align: left !important;
}

.dispCard {
  margin-bottom: 2%;
}

</style>
